package edu.gduf.service.impl;

import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import edu.gduf.dao.SigninMapper;
import edu.gduf.dao.SstMapper;
import edu.gduf.entity.QRCode;
import edu.gduf.entity.Signin;
import edu.gduf.entity.Sst;
import edu.gduf.entity.Student;
import edu.gduf.service.QRCodeService;
import edu.gduf.service.StudentService;

/**
 * 
 * @author hhx
 *
 */
@Service
public class QRCodeServiceImp implements QRCodeService {
	@Autowired
	private QRCode qrcode;
	@Autowired
	private StudentService studentservice;
	@Autowired
	private SigninMapper signinMapper;

	@Autowired
	private SstMapper sstMapper;

	@Override
	public void createQRCode(int tid, long startTime, long endTime, int classId, String courceName,
			OutputStream out) {
		try {


			// 二维码以json传输数据,Android端fastjson反序列化得到javabean ->
			// edu.gduf.dto.QRCodeDTO
			Sst sst = new Sst();
			sst.setStarttime(startTime);
			sst.setTid(tid);
			sst.setClassname(courceName);
			sstMapper.insert(sst);
			Thread thread = new Thread() {
				@Override
				public void run() {
					List<Student> students = studentservice.selectByClassId(classId);
					for (Student student : students) {
						Signin signin = new Signin();
						signin.settId(tid);
						signin.setStarttime(startTime);
						signin.setEndtime(endTime);
						signin.setClassId(classId);
						signin.setCourceName(courceName);
						signin.setStuId(student.getStuId());
						signin.setStuName(student.getStuName());
						signinMapper.insert(signin);
					}

				}
			};
			thread.start();
			 
			


		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void getQRCode(OutputStream out, String content) throws Exception {
		HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
		hints.put(EncodeHintType.CHARACTER_SET, qrcode.getCharset());


		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE,
				qrcode.getWidth(), qrcode.getHeight(), hints);

		BufferedImage image = new BufferedImage(qrcode.getWidth(), qrcode.getWidth(), BufferedImage.TYPE_INT_RGB);

		MatrixToImageWriter.writeToStream(bitMatrix, qrcode.getFormat(), out);
	}


}
